package com.example.smartplay.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.smartplay.entity.Club;
import com.example.smartplay.entity.Result;
import com.example.smartplay.entity.Student;
import com.example.smartplay.entity.User;
import com.example.smartplay.mapper.ClubMapper;
import com.example.smartplay.mapper.StudentMapper;
import com.example.smartplay.mapper.UserMapper;
import com.example.smartplay.service.ClubService;
import com.example.smartplay.service.StudentService;
import com.example.smartplay.service.UserService;
import com.example.smartplay.utils.EmailUtil;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 
 * @since 2024-07-11
 */
@Slf4j
@RestController
@RequestMapping("/club")
public class ClubController {

    @Autowired
    private ClubService clubService;
    @Autowired
    private ClubMapper clubMapper;
    @Autowired
    private StudentMapper StudentMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    EmailUtil emailUtil;


    //查询社团
    @GetMapping
    public Result getAll()
    {
        return Result.success(clubService.list());
    }

/*    // 分页查询获取社团
    @GetMapping("/getclub/{pageNum}/{pageSize}")
    public Result getclub(
            @PathVariable("pageNum") Integer pageNum,
            @PathVariable("pageSize") Integer pageSize
    )
    {
        LambdaQueryWrapper<Club> wrapper = new LambdaQueryWrapper<>();
        Page<Club> page = new Page<>(pageNum, pageSize);
        clubService.page(page, wrapper);
        return Result.success(page);

    }*/

    //查询社团
   @GetMapping("/getclubs/{pageNum}/{pageSize}")
    public Result getclubs(
           @RequestParam(value = "clubId",required = false) Integer clubId,
            @PathVariable("pageNum") Integer pageNum,
            @PathVariable("pageSize") Integer pageSize
    )
    {

        System.out.println("pageNum = " + pageNum);
        System.out.println("pageSize = " + pageSize);
        // 查询总记录数
        int total = clubMapper.countClubs();

        // 查询分页数据
        List<Club> clubs = clubMapper.selectClubWithStudentName(clubId,pageNum, pageSize);

        // 构建返回结果，包括分页数据和总记录数
        Map<String, Object> result = new HashMap<>();
        result.put("total", total);
        result.put("data", clubs);

        return Result.success(result);
    }
    /*  @GetMapping("/getclubs/{pageNum}/{pageSize}")
       public MyResponeData getclubs(
               @PathVariable("pageNum") Integer pageNum,
               @PathVariable("pageSize") Integer pageSize
       )
       {
           MyResponeData data = new MyResponeData();
           data.setErrorCode(0);
           data.setErrorMsg("操作成功");
           data.setArg(4);
           data.setDataList(clubMapper.selectClubWithStudentName(pageNum,pageSize));
           System.out.println("pageNum = " + pageNum);
           System.out.println("pageSize = " + pageSize);
           return data;
       }*/
    //增加或者修改社团
   /* @PostMapping("/saveOrUpdate")
    public Result saveOrUpdate(@RequestBody Club club)
    {
        //  判断所选择的学生clubid是否为空 也就是是否担任社团社长
      Club club1 =  clubMapper.selectByStudentId(club.getStudentId());
      //如果club1不为空 说明添加失败
        if (club1!=null)
        {
            return Result.error("该学生已担任其他社团社长");
        }

        club.setStudentId(club.getStudentId());
        clubService.saveOrUpdate(club);
        //往user表里该学生的社团信息同步clubid
        User user = UserMapper.selectById(club.getStudentId());
        user.setClubId(club.getId());
        UserMapper.updateById(user);
        return Result.success();
    }*/
    //添加社团
    @PostMapping("/save")
    public Result save(@RequestBody Club club)
    {
        //  判断所选择的学生clubid是否为空 也就是是否担任社团社长
        User user =  userMapper.selectByStudentId(club.getStudentId());

        //如果user.clubid不为空 说明添加失败
        if (user != null && user.getClubId() != null)
        {
            return Result.error("该学生已担任其他社团社长");
        }


        clubService.save(club);
        // 更新用户表中该学生的社团信息
        if (user != null) {
            user.setClubId(club.getId());
            userMapper.updateById(user);
        }

        return Result.success();
    }

/*
    // 修改社团
    @PutMapping("/update")
    @Transactional // 添加事务注解
    public Result update(@RequestBody Club club) {
        // 获取当前社团的信息
        Club currentClub = clubService.getById(club.getId());
        if (currentClub == null) {
            return Result.error("社团不存在");
        }

        // 判断当前社团的社长是否改变
        if (!currentClub.getStudentId().equals(club.getStudentId())) {
            // 如果社长改变，判断新的社长是否已经担任其他社团社长
            User newUser = userMapper.selectByStudentId(club.getStudentId());
            if (newUser != null && newUser.getClubId() != null) {
                return Result.error("该学生已担任其他社团社长");
            }
        }

        // 更新社团信息
        clubService.updateById(club);

        // 更新用户表中社长的社团信息
        User currentUser = userMapper.selectByStudentId(currentClub.getStudentId());
        if (currentUser != null && currentUser.getClubId() != null && currentUser.getClubId().equals(club.getId())) {
            currentUser.setClubId(null);
            userMapper.updateById(currentUser);
        }

        // 如果新的社长不为空，更新其在用户表中的社团信息
        if (!currentClub.getStudentId().equals(club.getStudentId())) {
            User newClubLeader = userMapper.selectByStudentId(club.getStudentId());
            if (newClubLeader != null) {
                newClubLeader.setClubId(club.getId());
                userMapper.updateById(newClubLeader);
            }
        }else if (club.getStudentId() == null) {
            // 如果新的社长为空，则清空社团的 studentId
            log.info("新的社长为空，将清空社团的 studentId");
            currentClub.setStudentId(null);
            // 执行更新操作
            clubService.updateById(currentClub);
            log.info("社团信息更新成功：{}", currentClub.getStudentId());

            // 同时清空之前社长的 clubId
            if (currentUser != null && currentUser.getClubId() != null && currentUser.getClubId().equals(club.getId())) {
                currentUser.setClubId(null);
                userMapper.updateById(currentUser);
            }
        }


        return Result.success();
    }
*/
/*@PutMapping("/update")
public Result update(@RequestBody Club club) {
    // 获取原社团信息
    Club existingClub = clubService.getById(club.getId());
    if (existingClub == null) {
        return Result.error("找不到该社团");
    }

    // 获取原社团的社长信息
    User existingPresident = userMapper.selectByClubId(existingClub.getId());

    // 判断所选择的学生是否已经担任其他社团社长
    User user = userMapper.selectByStudentId(club.getStudentId());

    //如果原社长为空 则判断新社长是否已经担任其他社团社长
    if (existingPresident == null) {
        // 如果原社长为空，则判断新社长是否已经担任其他社团社长
        if (user != null && user.getClubId() != null) {
            return Result.error("该学生已担任其他社团社长");
        }

        else if (club.getStudentId() != null) {
            existingClub.setStudentId(club.getStudentId());
            clubService.updateById(existingClub);
        }
    }

    // 如果新社长不为空，并且不是原社团的社长，且已经担任其他社团社长，则返回错误
    if (user != null && user.getClubId() != null && !user.getClubId().equals(club.getId())) {
        return Result.error("该学生已担任其他社团社长");
    }

    // 如果原社长不为空，并且新社长与原社长不同，则需要清除原社长的clubid信息
    if (existingPresident != null && !existingPresident.getStudentId().equals(club.getStudentId())) {
        existingPresident.setClubId(null);
        userMapper.updateById(existingPresident);
    }

    // 更新社团信息
    clubService.updateById(club);

    // 更新新社长的社团信息
    if (user != null) {
        user.setClubId(club.getId());
        userMapper.updateById(user);
    }

    // 如果新社长为空，则清空社团的学生ID和原社团的社长信息
    if (user == null) {
        club.setStudentId(null);
        if (existingPresident != null) {
            existingPresident.setClubId(null);
            userMapper.updateById(existingPresident);
        }
    }

    return Result.success();
}*/

    @PutMapping("/update")
    public Result update(@RequestBody Club club) {
        // 获取当前社团的信息
        Club currentClub = clubService.getById(club.getId());
        if (currentClub == null) {
            return Result.error("社团不存在");
        }

        // 获取当前社团的社长信息
        User currentLeader = userMapper.selectByStudentId(currentClub.getStudentId());

        // 判断原社长是否为空
        if (currentLeader == null) {
            // 原社长为空，判断新社长是否已经担任其他社团社长
            User newLeader = userMapper.selectByStudentId(club.getStudentId());
            if (newLeader != null && newLeader.getClubId() != null) {
                return Result.error("该学生已担任其他社团社长");
            }

            // 更新新社长在用户表中的社团信息
            if (newLeader != null) {
                newLeader.setClubId(club.getId());
                userMapper.updateById(newLeader);
            }
        } else {
            // 原社长不为空，判断新社长是否和原社长相同
            if (!currentClub.getStudentId().equals(club.getStudentId())) {
                // 新社长不同于原社长，处理新社长信息
                if (club.getStudentId() == null) {
                    // 如果新社长为空，则清空原社团的社长信息
                    currentClub.setStudentId(null);
                    clubService.updateById(currentClub);

                    // 同时清空之前社长的 clubId
                    if (currentLeader.getClubId() != null && currentLeader.getClubId().equals(club.getId())) {
                        currentLeader.setClubId(null);
                        userMapper.updateById(currentLeader);
                    }
                } else {
                    // 新社长不为空，判断新社长是否已经担任其他社团社长
                    User newLeader = userMapper.selectByStudentId(club.getStudentId());
                    if (newLeader != null && newLeader.getClubId() != null) {
                        return Result.error("该学生已担任其他社团社长");
                    }

                    // 更新新社长在用户表中的社团信息
                    if (newLeader != null) {
                        newLeader.setClubId(club.getId());
                        userMapper.updateById(newLeader);
                    }

                    // 清空原社长的社团信息
                    if (currentLeader.getClubId() != null && currentLeader.getClubId().equals(club.getId())) {
                        currentLeader.setClubId(null);
                        userMapper.updateById(currentLeader);
                    }
                }
            }
        }

        // 更新社团信息
        clubService.updateById(club);

        return Result.success();
    }
    //删除社团
    @DeleteMapping("{ids}")
    public Result delete(@PathVariable List<Integer> ids)
    {
        //判断删除的社团是否有studentid
        for (Integer id : ids) {
            Club club = clubMapper.selectById(id);
            if (club.getStudentId()!=null)
            {
                return Result.error("该社团已有社长，无法删除");
            }
        }

        clubService.removeByIds(ids);

        return Result.success();
    }



 /*   @GetMapping("/getAll")
    public Result getAll(Integer studentId){
        return Result.success(clubMapper.selectClubWithStudentName(studentId));
    }*/

    //发送验证码
    @GetMapping("/sendEmail")
    public Result sendEmail(String email, HttpSession session) {
        String code = RandomStringUtils.randomNumeric(4);
        session.setAttribute("register_email", email); // 注册时使用的邮箱
        session.setAttribute("register_code", code);  // 注册时使用的验证码
        emailUtil.sendSimpleMessage(email, "欢迎注册", "您的验证码为" + code);
        return Result.success(code);
    }

}
